#* application_contorller.rb
#* Copyright (C) 2010  Embian Inc.
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or 
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with This program.  If not, see <http://www.gnu.org/licenses/>.
#  
#* Filters added to this controller apply to all controllers in the application.
#  Likewise, all the methods added will be available for all controllers.
#* Author: KyoungMo Yang(E-mail : mo@embian.com)
#* Modified: 2010-12-06
#* References: N/A
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  before_filter :login_check, :except => [:login_proc, :login, :login_check, :logout]
  layout "app_layout"
  
  
  #* Functionailities
  # * Handling login process
  #* Parameters 
  # * HTTP POST
  #   * [uid] : user id
  #   * [upw] : user password
  #* Return
  # * N/A
  #* Note
  # * N/A
  def login
    uid = cookies[:uid]
    usession = cookies[:usession]
    logger.info "LOGIN uid : #{uid}"
    logger.info "LOGIN usession : #{usession}"
   if _is_login(uid, usession)
      _login_success_to
    end
  end
  
  #* Functionailities
  # * Handling login process
  #* Parameters 
  # * HTTP POST
  #   * [uid] : user id
  #   * [upw] : user password
  #* Return
  # * JSON
  #* Note
  # * N/A
  def login_proc
    uid = params[:uid]
    upw = params[:upw]
    message = nil

    unless uid
      logger.info "params : #{uid}, #{upw}"
      message = "Invalid ID"
      _send_to_client(false, message)
      return
    end
    
    unless upw
      logger.info "params : #{uid}, #{upw}"
      message = "Invalid Password"
      _send_to_client(false, message)
      return
    end
    
    user = User.find_by_uid(uid)
    unless user
      logger.info "User : #{user}"
      message = "'#{uid}' is an unregistered user. Please, join us.."
      _send_to_client(false, message)
      return
    end
    
    unless user.upw == upw
      logger.info "PW : #{user.upw} != #{upw}"
      message = "Wrong password"
      _send_to_client(false, message)
      return
    end
    
    usession = Digest::MD5.hexdigest("--my-salt--#{uid}--#{Time.now()}")
    user.usession = usession
    unless user.save
      logger.info "ERROR : #{user.errors.full_messages}"
      _send_to_client(false, 'System Error!!. Please contact system administrator (E-mail : mo@embian.com).')
      return 
    end
    cookies[:uid] = { :value => uid, :expires => 5.hour.from_now }
    cookies[:usession] = { :value => usession, :expires => 5.hour.from_now }
    
    _send_to_client(true, 'Login Success', {:redirect_to=>'/cat'})
  end
  
  #* Functionailities
  # * Handling logout process
  #* Parameters 
  # * HTTP POST
  # * N/A
  #* Return
  # * JSON
  #* Note
  # * N/A
  def logout
    cookies.delete :usession
    _login_failed_to
  end
  
  #* Functionailities
  # * Handling logout process
  #* Parameters 
  # * HTTP POST
  #   * [uid] : user id
  #   * [usession] : user session
  #* Return
  # * JSON
  #* Note
  # * N/A
  def login_check
    uid = cookies[:uid]
    usession = cookies[:usession]
    logger.info "LOGIN CHECK uid : #{uid}"
    logger.info "LOGIN CHECK usession : #{usession}"
    unless _is_login(uid, usession)
      _login_failed_to
    end
  end
  
  private
  #* Functionailities
  # * Redirect to login page
  #* Parameters 
  # * N/A
  #* Return
  # * N/A
  #* Note
  # * N/A
  def _login_failed_to
    redirect_to :action => "login"
  end
  
  #* Functionailities
  # * Redirect to main page
  #* Parameters 
  # * N/A
  #* Return
  # * N/A
  #* Note
  # * N/A
  def _login_success_to
    redirect_to '/cat'
  end
  
  #* Functionailities
  # * Check whether to login or not
  #* Parameters 
  # * [uid] : User#uid
  # * [usession] : User#usession
  #* Return
  # * [result] : returns true if login, otherwise returns false
  #* Note
  # * N/A
  def _is_login(uid, usession)
    return false unless uid || usession
    user = User.find_by_uid(uid)
    if user
      return user.usession == usession
    end
    
    return false
  end
  
  #* Functionailities
  # * Send result to client
  #* Parameters
  # * [uid] : User#uid
  # * [usession] : User#usession
  #* Return
  # * [result] : returns true if login, otherwise returns false
  #* Note
  # * N/A
  def _send_to_client(is_success, message=nil, data=nil)
    res = {}
    res[:message] = message
    res[:data] = data
    res[:success] = is_success
    
    respond_to do |format|
      format.json { render :json => res }
      format.xml { render :xml => res }
    end
  end
end
